package com.jb.java.tools;

import com.jb.web.bean.TextArea;
import com.jb.web.bean.custom.FileDirectory;
import com.jb.web.bean.custom.FileNode;
import com.jb.web.bean.event.UIEvent;
import com.jb.web.context.WebContext;
import com.jb.web.util.Filer;

import java.io.File;


public class FileEH {
    public void onSaveFile(WebContext pCtx, UIEvent event) {
        String value = event.getParameter("fileEditor");

        FileDirectory fd = (FileDirectory) pCtx.getRequestTree().getDescendantByClientId("fileDirectory");
        FileNode fn = fd.getSelected();
        File file = fn.getFile();

        if (file.isFile()) {
            TextArea tx = (TextArea) fd.getPage().getDescendantByClientId("fileEditor");
            tx.setValue(value);
            Filer.save(file, value);
        }
    }

    public void onSelectFile(WebContext pCtx, UIEvent event) {
        FileDirectory fd = (FileDirectory) event.getSource();
        FileNode fn = fd.getSelected();
        File file = fn.getFile();

        if (file.isFile()) {
            TextArea tx = (TextArea) fd.getPage().getDescendantByClientId("fileEditor");
            tx.setValue(Filer.read(file));
        }
    }
}
